package com.rimi.lzhg.controller;

import com.alibaba.fastjson.JSONObject;
import com.rimi.lzhg.response.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@CrossOrigin
@RestController
public class FileController {

    @PostMapping("/manager/upload")
    public Object upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.error("上传失败，请选择文件");
        }
        //文件原名
        String originalFilename = file.getOriginalFilename();
        //获取文件名
        int i = originalFilename.lastIndexOf(".");
        String fileName=null;
        if(i!=-1){
            fileName = originalFilename.substring(i);
        }
        fileName = System.currentTimeMillis()+fileName;
        //文件保存目录
        File filePath = new File(this.getClass().getClassLoader().getResource("").getPath()+"static/images");
        //文件保存路径
        File dest = new File(filePath + File.separator+fileName);
        //验证路径是否存在
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        try {
            file.transferTo(dest);
            return  ResponseEntity.success(new JSONObject().fluentPut("fileName",fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  ResponseEntity.error("文件保存到服务器失败!!!");
    }

}
